/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {void} Do not return anything, modify root in-place instead.
 */
var flatten = function (root) {
  if (root) {
    let lt = root.left
    let rt = root.right
    let flatRt = null
    let flatLt = null
    if (rt) {
      flatRt = flatten(rt)
    }
    if (lt) {

      flatLt = flatten(lt)
      let tail = flatLt
      while (tail.right) {
        tail = tail.right
      }
      tail.right = flatRt
      root.left = null
      root.right = flatLt
    }
  }
  return root
};

let t = {
  val: 1,
  left: {
    val: 2,
    left: {
      val: 3,
      left: null,
      right: null
    },
    right: {
      val: 4,
      left: null,
      right: null
    }
  },

  right: {
    val: 5,
    left: null,
    right: {
      val: 6,
      left: null,
      right: null
    }
  }
}

let res = flatten(t)
console.log(res);